package com.diligent.cloud.sfc.service.impl;

import com.alibaba.fastjson.JSON;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ListResult;
import com.canny.commons.model.ObjectResult;
import com.canny.commons.page.IPage;
import com.canny.commons.page.Pagination;
import com.diligent.cloud.logistics.container.enums.BoxFillDocStatus;
import com.diligent.cloud.logistics.container.enums.BoxStatus;
import com.diligent.cloud.logistics.container.model.LcmBoxFill;
import com.diligent.cloud.logistics.container.model.LcmBoxFillDetail;
import com.diligent.cloud.logistics.container.model.LcmBoxFillMaster;
import com.diligent.cloud.logistics.container.model.LcmBoxLedger;
import com.diligent.cloud.logistics.container.service.LcmBoxFillDetailFeignService;
import com.diligent.cloud.logistics.container.service.LcmBoxFillMasterFeignService;
import com.diligent.cloud.logistics.container.service.LcmBoxLedgerFeignService;
import com.diligent.cloud.primary.data.feign.service.mdm.MdmBaseFeignService;
import com.diligent.cloud.primary.data.feign.service.mdm.MdmMatTypeFeignService;
import com.diligent.cloud.primary.data.feign.service.rt.RtMachineFeignService;
import com.diligent.cloud.primary.data.feign.service.rt.RtWorkCenterFeignService;
import com.diligent.cloud.primary.data.model.Period;
import com.diligent.cloud.primary.data.model.Result;
import com.diligent.cloud.primary.data.model.mdm.MdmMatType;
import com.diligent.cloud.primary.data.model.rt.RtMachine;
import com.diligent.cloud.primary.data.model.rt.RtWorkCenter;
import com.diligent.cloud.prodbatch.model.MfgProdBatch;
import com.diligent.cloud.prodbatch.service.MfgProdBatchFeignService;
import com.diligent.cloud.sfc.config.OauthConfig;
import com.diligent.cloud.sfc.model.MatType;
import com.diligent.cloud.sfc.model.MfgConsume;
import com.diligent.cloud.sfc.model.OrderType;
import com.diligent.cloud.sfc.model.StationType;
import com.diligent.cloud.sfc.model.enums.Cwoc;
import com.diligent.cloud.sfc.model.info.*;
import com.diligent.cloud.sfc.model.info.inventory.MatInventoryInfo;
import com.diligent.cloud.sfc.model.params.OrderListParams;
import com.diligent.cloud.sfc.model.params.inventory.MatInfoParams;
import com.diligent.cloud.sfc.service.ISfcService;
import com.diligent.cloud.web.model.PageAndCondition;
import com.diligent.cloud.wip.core.feign.service.WipStorageLedgerFeignService;
import com.diligent.cloud.wip.core.vo.GuideDetail;
import com.diligent.cloud.wip.core.vo.GuideMaster;
import com.diligent.cloud.wip.panel.modle.WipStorageBin;
import com.diligent.cloud.wip.panel.modle.WipStorageLedger;
import com.diligent.cloud.workorder.enums.DocStatus;
import com.diligent.cloud.workorder.enums.WoOrderStatus;
import com.diligent.cloud.workorder.model.*;
import com.diligent.cloud.workorder.service.*;
import com.diligent.cloud.workordermd.feign.service.MfgConsumeDetailFeignService;
import com.diligent.cloud.workordermd.feign.service.MfgConsumeMasterFeignService;
import com.diligent.cloud.workordermd.feign.service.MfgMdApplyUseFeignService;
import com.diligent.cloud.workordermd.feign.service.MfgUserEnvironmentFeignService;
import com.diligent.cloud.workordermd.model.MfgConsumeDetail;
import com.diligent.cloud.workordermd.model.MfgConsumeMaster;
import com.diligent.cloud.workordermd.model.MfgMdApplyUse;
import com.diligent.cloud.workordermd.model.MfgUserEnvironment;
import com.diligent.foundation.data.model.v2.Condition;
import com.google.common.base.Preconditions;
import io.swagger.models.auth.In;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ISfcBaseServiceImpl class
 *
 * @author xf107278
 * @date 3/28/2020
 */
@Service
public class SfcBaseServiceImpl implements ISfcService {
    private WoOrderFeignService orderFeignService;
    private WoOrderCompleteDetailFeignService woOrderCompleteDetailFeignService;
    private LcmBoxLedgerFeignService lcmBoxLedgerFeignService;
    private LcmBoxFillDetailFeignService lcmBoxFillDetailFeignService;
    private LcmBoxFillMasterFeignService lcmBoxFillMasterFeignService;
    private MfgConsumeMasterFeignService mfgConsumeMasterFeignService;
    private MfgMdApplyUseFeignService mfgMdApplyUseFeignService;
    private final WoOrderMatNeedFeignService orderMatNeedFeignService;
    private MfgConsumeDetailFeignService mfgConsumeDetailFeignService;
    private MfgUserEnvironmentFeignService mfgUserEnvironmentFeignService;
    private MfgProdBatchFeignService mfgProdBatchFeignService;
    private MdmMatTypeFeignService mdmMatTypeFeignService;
    private RtMachineFeignService rtMachineFeignService;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private RtWorkCenterFeignService rtWorkCenterFeignService;
    private final WipStorageLedgerFeignService wipStorageLedgerFeignService;

    private WoOperationCompleteDetailFeignService operationCompleteDetailFeignService;
    private final WoOperationCompleteFeignService operationCompleteFeignService;
    private final WoOperationCompleteMasterFeignService operationCompleteMasterFeignService;
    private final OauthConfig.RequestParams requestParams;
    private final MdmBaseFeignService mdmBaseFeignService;
    private final WoOrderCompleteMasterFeignService orderCompleteMasterFeignService;

    public SfcBaseServiceImpl(WoOrderFeignService orderFeignService,
                              WoOrderCompleteDetailFeignService woOrderCompleteDetailFeignService,
                              LcmBoxLedgerFeignService lcmBoxLedgerFeignService,
                              LcmBoxFillDetailFeignService lcmBoxFillDetailFeignService,
                              LcmBoxFillMasterFeignService lcmBoxFillMasterFeignService,
                              MfgConsumeMasterFeignService mfgConsumeMasterFeignService,
                              MfgMdApplyUseFeignService mfgMdApplyUseFeignService,
                              WoOrderMatNeedFeignService orderMatNeedFeignService,
                              MfgConsumeDetailFeignService mfgConsumeDetailFeignService,
                              MfgUserEnvironmentFeignService mfgUserEnvironmentFeignService,
                              MfgProdBatchFeignService mfgProdBatchFeignService,
                              MdmMatTypeFeignService mdmMatTypeFeignService,
                              RtMachineFeignService rtMachineFeignService,
                              RtWorkCenterFeignService rtWorkCenterFeignService,
                              WipStorageLedgerFeignService wipStorageLedgerFeignService,
                              WoOperationCompleteDetailFeignService operationCompleteDetailFeignService,
                              WoOperationCompleteFeignService operationCompleteFeignService,
                              WoOperationCompleteMasterFeignService operationCompleteMasterFeignService,
                              OauthConfig.RequestParams requestParams, MdmBaseFeignService mdmBaseFeignService,
                              WoOrderCompleteMasterFeignService orderCompleteMasterFeignService) {
        this.orderFeignService = orderFeignService;
        this.woOrderCompleteDetailFeignService = woOrderCompleteDetailFeignService;
        this.lcmBoxLedgerFeignService = lcmBoxLedgerFeignService;
        this.lcmBoxFillDetailFeignService = lcmBoxFillDetailFeignService;
        this.lcmBoxFillMasterFeignService = lcmBoxFillMasterFeignService;
        this.mfgConsumeMasterFeignService = mfgConsumeMasterFeignService;
        this.mfgMdApplyUseFeignService = mfgMdApplyUseFeignService;
        this.orderMatNeedFeignService = orderMatNeedFeignService;
        this.mfgConsumeDetailFeignService = mfgConsumeDetailFeignService;
        this.mfgUserEnvironmentFeignService = mfgUserEnvironmentFeignService;
        this.mfgProdBatchFeignService = mfgProdBatchFeignService;
        this.mdmMatTypeFeignService = mdmMatTypeFeignService;
        this.rtMachineFeignService = rtMachineFeignService;
        this.rtWorkCenterFeignService = rtWorkCenterFeignService;
        this.wipStorageLedgerFeignService = wipStorageLedgerFeignService;
        this.operationCompleteDetailFeignService = operationCompleteDetailFeignService;
        this.operationCompleteFeignService = operationCompleteFeignService;
        this.operationCompleteMasterFeignService = operationCompleteMasterFeignService;
        this.requestParams = requestParams;
        this.mdmBaseFeignService = mdmBaseFeignService;
        this.orderCompleteMasterFeignService = orderCompleteMasterFeignService;
    }

    @Override
    public List<WoOrder> getSameOrder(String machCode, Integer orderStatus, Integer orderType, Long systemId,
                                      Date produceDate) {
        List<Condition> conditions = new ArrayList<>();
        Condition orderTypeCondition = new Condition("orderType", "eq", orderType, null);
        Condition orderStatusCondition = new Condition("orderStatus", "eq", orderStatus, null);
        Condition machCodeCondition = new Condition("machineCode", "eq", machCode, null);
        Condition systemIdStatusCondition = new Condition("systemId", "eq", systemId, null);
        Condition produceDateCondition = new Condition("produceDate", "eq", simpleDateFormat.format(produceDate), null);

        conditions.add(machCodeCondition);
        conditions.add(systemIdStatusCondition);
        conditions.add(orderTypeCondition);
        conditions.add(orderStatusCondition);
        conditions.add(produceDateCondition);

        Pagination pagination = new Pagination(1L, 1000000000L);
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setConditions(conditions);
        pageAndCondition.setPagination(pagination);
        ResponseEntity<Result<IPage<WoOrder>>> page = orderFeignService.page(pageAndCondition);
//区分已完成工单？
//        Iterator<WoOrder> orderIterator = page.getBody().getData().getRecords().iterator();
//        while (orderIterator.hasNext()){
//            WoOrder order = orderIterator.next();
//            pageAndCondition.setConditions(Collections.singletonList(new Condition("woOrderId","eq",order.getId(),
//            null)));
//            ResponseEntity<Result<IPage<WoOrderCompleteDetail>>> orderCompleteDetailPage =
//                    orderCompleteDetailFeignService.page(pageAndCondition);
//            if (orderCompleteDetailPage.getBody().getData().getRecords().size()!=0){
//                orderIterator.remove();
//            }
//        }

        if (page.getBody() != null && page.getBody().getCode() == 0) {
            IPage<WoOrder> orderIPage = page.getBody().getData();
            return orderIPage.getRecords();
        } else {
            return null;
        }
    }

    @Override
    public WoOrderCompleteDetail getOrderCompleteByOrder(Long orderId, String woOrder) {
        ArrayList<Condition> conditions = new ArrayList();
        if (orderId != null) {
            conditions.add(new Condition("woOrderId", "eq", orderId, null));
        }
        if (woOrder != null) {
            conditions.add(new Condition("woOrder", "eq", woOrder, null));
        }

        Pagination pagination = new Pagination(1L, 10000L);
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(pagination);
        pageAndCondition.setConditions(conditions);


        ResponseEntity<Result<IPage<WoOrderCompleteDetail>>> page =
                woOrderCompleteDetailFeignService.page(pageAndCondition);
        if (page.getBody() != null && page.getBody().getData() != null) {
            for (WoOrderCompleteDetail orderCompleteDetail : page.getBody().getData().getRecords()) {
                conditions = new ArrayList<>();
                conditions.add(new Condition("isClosed", "eq", 0, null));
                conditions.add(new Condition("isCanceled", "eq", 0, null));
                conditions.add(new Condition("id", "eq", orderCompleteDetail.getMasterId(), null));
                pageAndCondition.setConditions(conditions);
                pageAndCondition.setPagination(new Pagination(1L, 1L));
                ResponseEntity<Result<IPage<WoOrderCompleteMaster>>> orderCompleteMasterPage =
                        orderCompleteMasterFeignService.page(pageAndCondition);
                if (orderCompleteMasterPage.getBody() != null && orderCompleteMasterPage.getBody().getData().getRecords().size() == 0) {
                    continue;
                }
                return orderCompleteDetail;
            }
        }
        return null;
    }


    @Override
    public WoOperationCompleteDetail getOperationCompleteDetailByWoOrder(String woOrder) {
        PageAndCondition pageAndCondition = new PageAndCondition();
        List<Condition> conditions = new ArrayList<>();
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        conditions.add(new Condition("woOrder", "eq", woOrder, null));
        conditions.add(new Condition("endTime", "nn", 1, null));
        pageAndCondition.setConditions(conditions);
        ResponseEntity<Result<IPage<WoOperationCompleteDetail>>> operationCompleteDetailPage =
                operationCompleteDetailFeignService.page(pageAndCondition);
        if (operationCompleteDetailPage.getBody() != null && operationCompleteDetailPage.getBody().getData().getRecords().size() != 0) {
            WoOperationCompleteDetail operationCompleteDetail =
                    operationCompleteDetailPage.getBody().getData().getRecords().stream().findFirst().get();
            conditions = new ArrayList<>();
            conditions.add(new Condition("id", "eq", operationCompleteDetail.getMasterId(), null));
            conditions.add(new Condition("isCanceled", "eq", "0", null));
            pageAndCondition.setConditions(conditions);
            ResponseEntity<Result<IPage<WoOperationCompleteMaster>>> operationCompleteMasterPage =
                    operationCompleteMasterFeignService.page(pageAndCondition);
            if (operationCompleteMasterPage.getBody().getData().getRecords().size() != 0) {
                return operationCompleteDetail;
            }
        }

        return null;
    }


    @Override
    public IPage<LcmBoxLedger> getIdleBox(String location, Long pageIndex, Long pageSize) {
        PageAndCondition pageAndCondition =
                new PageAndCondition();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("state", "in",
                BoxStatus.NORMAL.getStatus() + "," + BoxStatus.INSTALLING.getStatus(), null));
        if (!"null".equalsIgnoreCase(location)) {
            conditions.add(new Condition("location", "eq", location, null));
        }
        Pagination pagination = new Pagination(pageIndex, pageSize);
        pageAndCondition.setPagination(pagination);
        pageAndCondition.setConditions(conditions);

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> search =
                lcmBoxLedgerFeignService.search(pageAndCondition);
        if (search.getBody() != null && search.getBody().getCode() == 0) {
            IPage<LcmBoxLedger> data = (IPage<LcmBoxLedger>) search.getBody().getData();
            return data;
        } else {
            return null;
        }
    }


    @Override
    public IPage<LcmBoxLedger> getLogisticsTransPortInfo(String location) {
        PageAndCondition pageAndCondition =
                new PageAndCondition();
        List<Condition> conditions = new ArrayList<>();
        Pagination pagination = new Pagination(1L, 100000L);
        Condition locationCondition = new Condition("location", "eq", location, null);
        Condition state = new Condition("state", "in",
                BoxStatus.INSTALLED.getStatus() + "," + BoxStatus.INSTALLING.getStatus(), null);
        conditions.add(state);
        conditions.add(locationCondition);
        pageAndCondition.setConditions(conditions);
        pageAndCondition.setPagination(pagination);

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> search =
                lcmBoxLedgerFeignService.search(pageAndCondition);
        if (search.getBody() != null && search.getBody().getData() != null) {
            return (IPage<LcmBoxLedger>) search.getBody().getData();
        } else {
            return null;
        }
    }

    @Override
    public List<LcmBoxFill> getOrderSameLocation(String location, Long orderId, String matType) {
        List<LcmBoxFill> answer = new ArrayList<>();
        Pagination pagination = new Pagination(1L, 100000L);
        //获取当前地方已使用的框
        IPage<LcmBoxLedger> bufferData = getLogisticsTransPortInfo(location);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> orderResponseEntity =
                orderFeignService.selectById(orderId);
        Preconditions.checkNotNull(orderResponseEntity.getBody(), "查询不到实体");
        Preconditions.checkNotNull(orderResponseEntity.getBody().getData(), "查询不到实体");
        WoOrder woOrder = (WoOrder) orderResponseEntity.getBody().getData();
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(pagination);
        for (LcmBoxLedger lcmBoxLedger : bufferData.getRecords()) {
            //获取工单

            pageAndCondition.setConditions(Collections.singletonList(new Condition("refBoxCode", "eq",
                    lcmBoxLedger.getCode(), null)));
            ResponseEntity<Result<IPage<LcmBoxFillDetail>>> boxFillDetailResult =
                    lcmBoxFillDetailFeignService.page(pageAndCondition);
            if (boxFillDetailResult.getBody() == null) {
                continue;
            }
            for (LcmBoxFillDetail boxFillDetail : boxFillDetailResult.getBody().getData().getRecords()) {
                ResponseEntity<Result> boxFillMasterResult =
                        lcmBoxFillMasterFeignService.selectById(boxFillDetail.getMasterId());
                Preconditions.checkNotNull(boxFillMasterResult.getBody(), "查询不到id为[%s]的消耗主表",
                        boxFillDetail.getMasterId());
                Preconditions.checkNotNull(boxFillMasterResult.getBody().getData(), "查询不到id为[%s]的消耗主表",
                        boxFillDetail.getMasterId());
                LcmBoxFillMaster boxFillMaster = (LcmBoxFillMaster) boxFillMasterResult.getBody().getData();
                if (BoxFillDocStatus.INSERT.getStatus().equals(boxFillMaster.getDocStatus())) {
                    ResponseEntity<Result> orderResult =
                            orderFeignService.selectById(Long.valueOf(boxFillDetail.getRefWoOrder()));
                    Preconditions.checkNotNull(orderResult.getBody(), "查询不到id为[%s]的工单",
                            boxFillDetail.getRefWoOrder());
                    Preconditions.checkNotNull(orderResult.getBody().getData(), "查询不到id为[%s]的工单",
                            boxFillDetail.getRefWoOrder());
                    WoOrder order = (WoOrder) orderResult.getBody().getData();

                    //查询所需物料
                    if (MatType.粉末.equalsIgnoreCase(matType)) {
                        if (order.getColorGroupCode().equalsIgnoreCase(woOrder.getColorGroupCode())) {
                            LcmBoxFill lcmBoxFill = new LcmBoxFill();
                            lcmBoxFill.setLcmBoxFillDetail(boxFillDetail);
                            lcmBoxFill.setLcmBoxFillMaster(boxFillMaster);
                            answer.add(lcmBoxFill);
                        }
                    } else {
                        //获取物料得对应类
                        String orderMatType = getMatCodeByOrderIdAndSystemId(order.getId(),
                                order.getSystemId(), matType);
                        String woOrderMatType = getMatCodeByOrderIdAndSystemId(woOrder.getId(),
                                woOrder.getSystemId(), matType);
                        if (orderMatType.equalsIgnoreCase(woOrderMatType)) {
                            LcmBoxFill lcmBoxFill = new LcmBoxFill();
                            lcmBoxFill.setLcmBoxFillDetail(boxFillDetail);
                            lcmBoxFill.setLcmBoxFillMaster(boxFillMaster);
                            answer.add(lcmBoxFill);
                        }
                    }
                }
            }
        }
        return answer;
    }

    @Override
    public RtMachine getMachineByMachCode(String machCode) {

        PageAndCondition pageAndCondition = new PageAndCondition();
        Pagination pagination = new Pagination(1L, 10000000000L);


        pageAndCondition.setConditions(Collections.singletonList(new Condition("machCode", "eq", machCode, null)));
        pageAndCondition.setPagination(pagination);


        ResponseEntity<Result<IPage<RtMachine>>> rtMachineResult =
                rtMachineFeignService.selectDataByConditionPage(pageAndCondition);

        if (rtMachineResult.getBody() != null && rtMachineResult.getBody().getData().getRecords().size() != 0) {
            IPage<RtMachine> machineIPage = rtMachineResult.getBody().getData();
            return machineIPage.getRecords().stream().findFirst().get();
        } else {
            return null;
        }

    }

    @Override
    public String getMatCodeByOrderIdAndSystemId(Long orderId, Long systemId, String matType) {
        PageAndCondition pageAndCondition = new PageAndCondition();
        Pagination pagination = new Pagination(1L, 1L);
        List<Condition> conditions = new ArrayList<>();

        ResponseEntity<Result> mdmMatTypeResult =
                mdmMatTypeFeignService.selectDataByCondition(Collections.singletonList(new Condition("name", "eq",
                        matType, null)));
        if (mdmMatTypeResult.getBody() != null && mdmMatTypeResult.getBody().getData() != null) {
            List<LinkedHashMap> matTypes = (List<LinkedHashMap>) mdmMatTypeResult.getBody().getData();
            if (matTypes.size() != 0) {
                MdmMatType mdmMatType = JSON.parseObject(JSON.toJSONString(matTypes.stream().findFirst().get()),
                        MdmMatType.class);
                pageAndCondition.setPagination(new Pagination(1L, 1L));
                conditions.add(new Condition("woOrderId", "eq", orderId, null));
                conditions.add(new Condition("systemId", "eq", systemId, null));
                conditions.add(new Condition("matType", "eq", mdmMatType.getCode(), null));

                pageAndCondition.setConditions(conditions);
                pageAndCondition.setPagination(pagination);
                ResponseEntity<Result<IPage<WoOrderMatNeed>>> page = orderMatNeedFeignService.page(pageAndCondition);
                if (page.getBody() != null && page.getBody().getData().getRecords().size() != 0) {
                    return page.getBody().getData().getRecords().stream().findFirst().get().getMatCode();
                } else {
                    return null;
                }
            }
        }
        return null;
    }

    @Override
    public String getBatchCodeByOrderId(Long orderId, String matCode) {
        List<WoOrderMatNeed> orderMatNeeds = getMatNeedByOrderIdAndMatType(orderId, null);
        Preconditions.checkNotNull(orderMatNeeds, String.format("查询不到此[%s]工单物料", orderId));

        String batchCode = null;
        for (WoOrderMatNeed woOrderMatNeed : orderMatNeeds) {
            if (!(woOrderMatNeed.getMatCode().equalsIgnoreCase(matCode))) {
                continue;
            }
            ResponseEntity<Result> matTypeResult =
                    mdmMatTypeFeignService.selectDataByCondition(Collections.singletonList(new Condition("code", "eq"
                            , woOrderMatNeed.getMatType(), null)));
            if (matTypeResult.getBody() == null && ((List<LinkedHashMap>) matTypeResult.getBody().getData()).size() == 0) {
                return null;
            }

            List<LinkedHashMap> matTypes = (List<LinkedHashMap>) matTypeResult.getBody().getData();
            MdmMatType mdmMatType = JSON.parseObject(JSON.toJSONString(matTypes.stream().findFirst().get()),
                    MdmMatType.class);

            //TODO 根据工单物料需求得出模具、铝棒后，需要分别查消耗表和模具上机表获取batchCode
            //TODO 利用物料编码、batchCode查出线边仓库存
            //TODO 查出库存数/当前型号模具需求数=同型号模具备料率
            switch (mdmMatType.getName()) {
                //模具
                case MatType.模具:
                    ResponseEntity<Result> mdApplyUseResult =
                            mfgMdApplyUseFeignService.selectDataByCondition(Collections.singletonList(new Condition(
                                    "matCodeCv", "eq", woOrderMatNeed.getMatCode(), null)));
                    if (mdApplyUseResult.getBody() != null && mdApplyUseResult.getBody().getData() != null) {
                        List<LinkedHashMap> mdApplyUses = (List<LinkedHashMap>) mdApplyUseResult.getBody().getData();
                        if (mdApplyUses.size() != 0) {
                            //TODO 逻辑判断？是否为一样的BachCode
                            MfgMdApplyUse mfgMdApplyUse =
                                    JSON.parseObject(JSON.toJSONString(mdApplyUses.stream().findFirst().get()),
                                            MfgMdApplyUse.class);
                            batchCode = mfgMdApplyUse.getBatchCode();
                        }
                    }
                    break;
                //铝棒
                case MatType.铝棒:
                case MatType.粉末:
                case MatType.包装物:
                case MatType.胶条:
                    ResponseEntity<Result> consumeMasterResult =
                            mfgConsumeMasterFeignService.selectDataByCondition(Collections.singletonList(new Condition("matCode", "eq", woOrderMatNeed.getMatCode(), null)));
                    if (consumeMasterResult.getBody() != null && consumeMasterResult.getBody().getData() != null) {
                        List<LinkedHashMap> consumeMasters =
                                (List<LinkedHashMap>) consumeMasterResult.getBody().getData();
                        if (consumeMasters.size() != 0) {
                            MfgConsumeMaster consumeMaster =
                                    JSON.parseObject(JSON.toJSONString(consumeMasters.stream().findFirst().get()),
                                            MfgConsumeMaster.class);
                            ResponseEntity<Result> consumeDetailResult =
                                    mfgConsumeDetailFeignService.selectDataByCondition(Collections.singletonList(new Condition("masterId", "eq", consumeMaster.getId(), null)));
                            List<LinkedHashMap> consumeDetails =
                                    (List<LinkedHashMap>) consumeDetailResult.getBody().getData();
                            if (consumeDetails.size() != 0) {
                                MfgConsumeDetail mfgConsumeDetail =
                                        JSON.parseObject(JSON.toJSONString(consumeDetails.stream().findFirst().get()),
                                                MfgConsumeDetail.class);
                                batchCode = mfgConsumeDetail.getBatchCode();
                            }
                        }
                    }
                    break;
            }
        }
        return batchCode;
    }

    @Override
    public List<WoOrderMatNeed> getMatNeedByOrderIdAndMatType(Long orderId, String matType) {
        PageAndCondition matNeedCondition = new PageAndCondition();
        matNeedCondition.setPagination(new Pagination(1L, 10000L));
        List<Condition> matNeedConditions = new ArrayList<>();
        matNeedConditions.add(new Condition("woOrderId", "eq", orderId, null));
        matNeedConditions.add(new Condition("isCanceled", "eq", 0, null));
        matNeedConditions.add(new Condition("isClosed", "eq", 0, null));
        if (matType != null) {
            matNeedConditions.add(new Condition("matType", "eq", matType, null));
        }
        matNeedCondition.setConditions(matNeedConditions);
        ResponseEntity<Result<IPage<WoOrderMatNeed>>> page = orderMatNeedFeignService.page(matNeedCondition);
        if (page.getBody() != null && page.getBody().getData() != null && page.getBody().getData().getRecords().size() != 0) {
            return page.getBody().getData().getRecords();
        }
        return null;
    }

    @Override
    public MfgUserEnvironment getUserEnvironmentByUserCode(String userCode) {
        ResponseEntity<Result> userEnvironmentRequest =
                mfgUserEnvironmentFeignService.selectDataByCondition(Collections.singletonList(new Condition(
                        "userCode", "eq", userCode, null)));
        if (userEnvironmentRequest.getBody() != null && userEnvironmentRequest.getBody().getData() != null) {
            List<LinkedHashMap> userEnvironments = (List<LinkedHashMap>) userEnvironmentRequest.getBody().getData();
            MfgUserEnvironment mfgUserEnvironment =
                    JSON.parseObject(JSON.toJSONString(userEnvironments.stream().findFirst().get()),
                            MfgUserEnvironment.class);
            return mfgUserEnvironment;
        } else {
            return null;
        }
    }

    @Override
    public ResponseEntity<ListResult> getCutOrderList(OrderListParams orderListParams) {
        WoOrderListParams woOrderListParams = new WoOrderListParams();
        woOrderListParams.setMachineCode(orderListParams.getMachineCode());
        woOrderListParams.setOrderStatus(WoOrderStatus.finish.getStatus());
        woOrderListParams.setOrderType(OrderType.挤压工单);

        if (orderListParams.getOrderType() == StationType.挂料工位.intValue() || orderListParams.getOrderType() == StationType.装框工位.intValue()) {
            woOrderListParams.setOperationIsFinished(1);
        } else {
            woOrderListParams.setOperationIsFinished(0);
        }

        woOrderListParams.setPageSize(orderListParams.getPageSize());
        woOrderListParams.setPageIndex(orderListParams.getPageIndex());
        woOrderListParams.setIsFinished(0);
        woOrderListParams.setMachineCode(orderListParams.getMachineCode());
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> responseEntity =
                orderFeignService.woOrderListFilter(woOrderListParams);

        ListResult listResult;
        if (responseEntity.getBody() != null && responseEntity.getBody().getData() != null) {
            Map map = (Map) responseEntity.getBody().getData();
            List<LinkedHashMap> orderList = (List<LinkedHashMap>) map.get("data");
            int total = (int) map.get("total");

            listResult = new ListResult(orderList);
            listResult.modifyCode(Codes.success, String.valueOf(total));

        } else {
            listResult = new ListResult();
        }
        return ResponseEntity.ok(listResult);
    }

    @Override
    public ResponseEntity<ListResult> getSameOrderByProdBatch(String prodBatch, String machCode, Long systemId,
                                                              Integer orderType, Integer isFinished,
                                                              Integer operationIsFinished) {
//        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgProdBatchesEntity =
//                mfgProdBatchFeignService.finishedProdBatchs(machCode, prodBatch, systemId);
//        com.diligent.cloud.primary.data.model.Result result = mfgProdBatchesEntity.getBody();
//        MfgProdBatch mfgProdBatch = (MfgProdBatch) result.getData();

        WoOrderListParams woOrderListParams = new WoOrderListParams();
        woOrderListParams.setMachineCode(machCode);
        woOrderListParams.setOrderStatus(WoOrderStatus.finish.getStatus());
        woOrderListParams.setProdBatch(prodBatch);
        woOrderListParams.setOperationIsFinished(operationIsFinished);
        woOrderListParams.setPageIndex(1L);
        woOrderListParams.setPageSize(100L);
//        if (mfgProdBatch.getEndTime() == null) {
//            woOrderListParams.setProdBatchEndTime(formatter.format(new Date()));
//        } else {
//            woOrderListParams.setProdBatchEndTime(formatter.format(mfgProdBatch.getEndTime()));
//        }
        if (orderType == StationType.挤压工位.intValue()) {
            woOrderListParams.setOrderType(orderType);
        } else if (orderType == StationType.剪切工位.intValue()) {
            woOrderListParams.setOrderType(OrderType.挤压工单);
        } else if (orderType == StationType.装框工位.intValue() || orderType == StationType.挂料工位.intValue()) {
            woOrderListParams.setOrderType(OrderType.挤压工单);
        } else if (orderType == StationType.喷涂上架工位.intValue() || orderType == StationType.喷涂上粉工位.intValue()) {
            woOrderListParams.setOrderType(OrderType.表面处理工单.intValue());
        } else if (orderType == StationType.穿条下架工位.intValue() || orderType == StationType.穿条工位.intValue()) {
            woOrderListParams.setOrderType(OrderType.后加工工单);
        } else if (orderType == StationType.包装下架工位.intValue() || orderType == StationType.包装工位.intValue()) {
            woOrderListParams.setOrderType(OrderType.包装工单.intValue());
        }


        // 0未完工
        woOrderListParams.setIsFinished(isFinished);
//        woOrderListParams.setProdBatchStartTime(formatter.format(mfgProdBatch.getBeginTime()));
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> responseEntity =
                orderFeignService.woOrderListFilter(woOrderListParams);
        Map map = (Map) responseEntity.getBody().getData();
        List<WoOrder> orders = (List<WoOrder>) map.get("data");

        String md = null;
        ResponseEntity<Result> byBatch = mfgProdBatchFeignService.getByBatch(prodBatch);
        if (byBatch.getBody() != null && byBatch.getBody().getCode() == 0) {
            ArrayList<LinkedHashMap> data = (ArrayList<LinkedHashMap>) byBatch.getBody().getData();
            MfgProdBatch mfgProdBatch = JSON.parseObject(JSON.toJSONString(data.stream().findFirst().get()),
                    MfgProdBatch.class);
            md = mfgProdBatch.getCv4();
        }
        ListResult result = new ListResult(orders);
        result.modifyCode(Codes.success.getCode(), md);
        return ResponseEntity.ok(result);
    }

    @Override
    public ListResult getMatList(String machCode, Integer orderType, String matCode) {
        List<Condition> conditions = new ArrayList<>();
        boolean machCodeIsNull = machCode == null ? true : "null".equalsIgnoreCase(machCode) ? true : false;
        boolean matCodeIsNull = matCode == null ? true : "null".equalsIgnoreCase(matCode) ? true : false;
        if (machCodeIsNull) {
            throw new NullPointerException("机台代码不能为空");
        } else if (matCodeIsNull) {
            throw new NullPointerException("物料代码不能为空");
        }

        if (!"ALL".equalsIgnoreCase(matCode)) {
            conditions.add(new Condition("matCode", "eq", matCode, null));
        }
        conditions.add(new Condition("machCode", "eq", machCode, null));
        conditions.add(new Condition("docStatus", "eq", 50, null));

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> consumerMasterResult =
                mfgConsumeMasterFeignService.selectDataByCondition(conditions);
        if (consumerMasterResult.getBody() != null && consumerMasterResult.getBody().getCode() == 0) {
            List<Object> infos = new ArrayList<>();

            List<LinkedHashMap> mfgConsumeMasters =
                    (List<LinkedHashMap>) consumerMasterResult.getBody().getData();
            for (LinkedHashMap linkedHashMap : mfgConsumeMasters) {
                MfgConsumeMaster mfgConsumeMaster = JSON.parseObject(JSON.toJSONString(linkedHashMap),
                        MfgConsumeMaster.class);

                if (OrderType.表面处理工单.equals(orderType)) {
                    ColorInfo colorInfo = new ColorInfo();
                    colorInfo.setId(mfgConsumeMaster.getId());
                    colorInfo.setColorCode(mfgConsumeMaster.getMatCode());
                    colorInfo.setColorName(mfgConsumeMaster.getMatName());
                    colorInfo.setColorType(mfgConsumeMaster.getMatType());
                    colorInfo.setReserveWeight(mfgConsumeMaster.getWeight().longValue());
                    //colorInfo.setTimeConsuming("5");
                    // colorInfo.setSendTime(mfgConsumeMaster.getUserTxt2());

                    colorInfo.setUpPowderOrderInfos(getBufferZoneAndAgingOrder(mfgConsumeMaster, orderType));
                    infos.add(colorInfo);
                } else if (OrderType.包装工单.equals(orderType)) {
                    PackagingInfo packagingInfo = new PackagingInfo();
                    packagingInfo.setId(mfgConsumeMaster.getId());
                    packagingInfo.setMatCode(mfgConsumeMaster.getMatCode());
                    packagingInfo.setMatName(mfgConsumeMaster.getMatName());
                    packagingInfo.setMatType(mfgConsumeMaster.getMatType());
                    packagingInfo.setReserveWeight(Long.valueOf(mfgConsumeMaster.getUserTxt2()));
                    packagingInfo.setTimeConsuming("5");
                    //TODO 相同颜色 位置？如何区分位置

                    packagingInfo.setPackagingOrderInfos(getBufferZoneAndAgingOrder(mfgConsumeMaster, orderType));
                    infos.add(packagingInfo);
                } else if (OrderType.后加工工单.equals(orderType)) {

                    RubberStripInfo rubberStripInfo = new RubberStripInfo();
                    rubberStripInfo.setId(mfgConsumeMaster.getId());
                    rubberStripInfo.setMatCode(mfgConsumeMaster.getMatCode());
                    rubberStripInfo.setMatName(mfgConsumeMaster.getMatName());
                    rubberStripInfo.setMatType(mfgConsumeMaster.getMatType());
                    rubberStripInfo.setSendTime("2020-03-12 17:00");
                    //rubberStripInfo.setReserveTotalLength(Long.valueOf(mfgConsumeMaster.getUserTxt2()));
                    rubberStripInfo.setRubberStripOrderInfos(getBufferZoneAndAgingOrder(mfgConsumeMaster, orderType));
                    infos.add(rubberStripInfo);
                }
            }
            return new ListResult<>(infos);
        } else {
            return new ListResult<>(new ArrayList<>());
        }
    }

    @Override
    public RtWorkCenter getWorkCenterByCwocCode(String workCenterCode) {
        ResponseEntity<Result> workCenterResult =
                rtWorkCenterFeignService.selectDataByCondition(Collections.singletonList(new Condition("cwocCode",
                        "eq", workCenterCode, null)));

        if (workCenterResult.getBody() != null && workCenterResult.getBody().getData() != null) {
            List<Map> list = (List<Map>) workCenterResult.getBody().getData();
            Map rtWorkCenterMap = list.stream().findFirst().get();
            RtWorkCenter rtWorkCenter = JSON.parseObject(JSON.toJSONString(rtWorkCenterMap), RtWorkCenter.class);
            return rtWorkCenter;
        } else {
            return null;
        }
    }

    private List<Object> getBufferZoneAndAgingOrder(MfgConsumeMaster mfgConsumeMaster, int orderType) {
        PageAndCondition pageAndCondition =
                new PageAndCondition();
        Pagination pagination = new Pagination(1L, 100000L);
        pageAndCondition.setPagination(pagination);
        List<Condition> conditions = new ArrayList<>();

        if (OrderType.表面处理工单.equals(orderType)) {
            conditions.add(new Condition("location", "in",
                    Cwoc.喷涂缓冲区.getCwocCode() + "," + Cwoc.时效.getCwocCode(), null));

        } else if (OrderType.包装工单.equals(orderType)) {

            conditions.add(new Condition("location", "eq",
                    Cwoc.包装缓冲区.getCwocCode(), null));

        } else if (OrderType.后加工工单.equals(orderType)) {
            conditions.add(new Condition("location", "eq",
                    Cwoc.穿条缓冲区.getCwocCode(), null));
        }

        Condition stateCondition = new Condition("state", "in",
                BoxStatus.INSTALLED.getStatus() + "," + BoxStatus.INSTALLING.getStatus(), null);

        conditions.add(stateCondition);

        pageAndCondition.setConditions(conditions);

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> boxLedgerResult =
                lcmBoxLedgerFeignService.search(pageAndCondition);

        List<Object> orderInfos = new ArrayList<>();

        if (boxLedgerResult.getBody() != null && boxLedgerResult.getBody().getData() != null &&
                ((IPage<LcmBoxLedger>) boxLedgerResult.getBody().getData()).getRecords().size() != 0) {
            IPage<LcmBoxLedger> lcmBoxLedgerIPage = (IPage<LcmBoxLedger>) boxLedgerResult.getBody().getData();

            List<Integer> orderStatus = new ArrayList<>();
            orderStatus.add(WoOrderStatus.scheduling.getStatus());
            orderStatus.add(WoOrderStatus.schedulings.getStatus());

            WoOrder order = null;
            for (LcmBoxLedger lcmBoxLedger : lcmBoxLedgerIPage.getRecords()) {

                pageAndCondition.setConditions(Collections.singletonList(new Condition("refBoxCode", "eq",
                        lcmBoxLedger.getCode(), null)));

                ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<LcmBoxFillDetail>>> lcmBoxFillDetailResult =
                        lcmBoxFillDetailFeignService.page(pageAndCondition);
                Preconditions.checkNotNull(lcmBoxFillDetailResult.getBody(), "查询不到装框单号");
                for (LcmBoxFillDetail lcmBoxFillDetail : lcmBoxFillDetailResult.getBody().getData().getRecords()) {
                    ResponseEntity<com.diligent.cloud.primary.data.model.Result> boxFillMasterResult =
                            lcmBoxFillMasterFeignService.selectById(lcmBoxFillDetail.getMasterId());
                    if (boxFillMasterResult.getBody() != null && boxFillMasterResult.getBody().getData() != null) {
                        LcmBoxFillMaster boxFillMaster = (LcmBoxFillMaster) boxFillMasterResult.getBody().getData();
                        if (BoxFillDocStatus.INSERT.getStatus().equals(boxFillMaster.getDocStatus())) {

                            ResponseEntity<Result> orderSelectOrderByIdResource =
                                    orderFeignService.selectById(Long.valueOf(lcmBoxFillDetail.getRefWoOrder()));
                            if (orderSelectOrderByIdResource.getBody() != null
                                    && orderSelectOrderByIdResource.getBody().getData() != null) {
                                order = (WoOrder) orderSelectOrderByIdResource.getBody().getData();
                            }
                        }
                    }
                }
                Preconditions.checkNotNull(order, "查询不到装框单号");
                if (OrderType.表面处理工单.equals(orderType)) {
                    String matCode = getMatCodeByOrderIdAndSystemId(order.getId(),
                            order.getSystemId(), MatType.粉末);
                    if (mfgConsumeMaster.getMatCode().equalsIgnoreCase(matCode)) {
                        UpPowderOrderInfo upPowderOrderInfo = new UpPowderOrderInfo()
                                .setColor(mfgConsumeMaster.getMatCode())
                                .setOrder(order.getWoOrder())
                                .setMatCode(mfgConsumeMaster.getUserTxt1())
                                .setPosition(lcmBoxLedger.getLocation())
                                .setGrade(1L)//TODO ←等级，↓拿总量？
                                .setDigit(lcmBoxLedger.getMatTotalDigit().longValue())
                                .setWeight(lcmBoxLedger.getWeight().longValue());
                        // 需求量？
//                        WoOrder order1 = sfcBaseService.getOrder(2, 100, lcmBoxLedger.getLoadBoxDocCode());
//                        Preconditions.checkNotNull(order1,"查不到剪切完成细节");
//                        WoOrderCompleteDetail orderCompleteDetail =
//                                sfcBaseService.getOrderCompleteDetail(order1.getId());
                        orderInfos.add(upPowderOrderInfo);

                    }
                } else if (OrderType.包装工单.equals(orderType)) {
                    String matCode = getMatCodeByOrderIdAndSystemId(order.getId(),
                            order.getSystemId(), MatType.包装物);
                    if (mfgConsumeMaster.getMatCode().equalsIgnoreCase(matCode)) {
                        PackagingOrderInfo packagingOrderInfo = new PackagingOrderInfo();
                        packagingOrderInfo.setOrder(order.getWoOrder());
                        packagingOrderInfo.setMatCode(order.getMatCode());
                        packagingOrderInfo.setPackaging(order.getMatCode());
                        packagingOrderInfo.setPosition(lcmBoxLedger.getLocation());
                        packagingOrderInfo.setGrade(1L);
                        packagingOrderInfo.setDigit(lcmBoxLedger.getMatTotalDigit().longValue());
                        packagingOrderInfo.setDigit(lcmBoxLedger.getMatTotalWeight().longValue());
                        orderInfos.add(packagingOrderInfo);
                    }
                } else if (OrderType.后加工工单.equals(orderType)) {
                    String matCode = getMatCodeByOrderIdAndSystemId(order.getId(),
                            order.getSystemId(), MatType.胶条);
                    if (mfgConsumeMaster.getMatCode().equalsIgnoreCase(matCode)) {
                        RubberStripOrderInfo rubberStripOrderInfo = new RubberStripOrderInfo();
                        rubberStripOrderInfo.setOrderCode(order.getWoOrder());
                        rubberStripOrderInfo.setRubberStrip(order.getMatCode());
                        rubberStripOrderInfo.setPosition(lcmBoxLedger.getLocation());
                        rubberStripOrderInfo.setGrade(1L);
                        rubberStripOrderInfo.setDigit(lcmBoxLedger.getMatTotalDigit().longValue());
                        rubberStripOrderInfo.setTotalLength(Long.valueOf(order.getCv4()) * lcmBoxLedger.getMatTotalDigit().longValue());
                        rubberStripOrderInfo.setTimeConsuming(3L);
                        rubberStripOrderInfo.setMatCode(mfgConsumeMaster.getUserTxt1());
                        orderInfos.add(rubberStripOrderInfo);
                    }
                }
            }
        }
        return orderInfos;
    }

    @Override
    public MfgConsume addMatConsumerInventory(MatInfoParams params, Principal principal) {
        MfgConsume mfgConsume = new MfgConsume();
        ResponseEntity<ObjectResult<Period>> periodId1 = mdmBaseFeignService.getPeriodId();
        Preconditions.checkNotNull(periodId1.getBody(), "查询不到periodId");
        long periodId = periodId1.getBody().getData().getId().longValue();

        MfgConsumeMaster consumeMaster = new MfgConsumeMaster();

        consumeMaster.setFormId(params.getFormId());
        //consumeMaster.setDocDate(new Date());
        //consumeMaster.setDocType(50);
        consumeMaster.setDocStatus(DocStatus.COMMIT.getStatus());
        consumeMaster.setSystemId(requestParams.getSystemId());
        consumeMaster.setCompanyId(requestParams.getCompanyId());
        consumeMaster.setPeriodId(periodId);

        MfgUserEnvironment userEnvironmentByUserCode = getUserEnvironmentByUserCode(principal.getName());
        consumeMaster.setCrewCode(userEnvironmentByUserCode.getCrewCode());
        consumeMaster.setCrewName(userEnvironmentByUserCode.getCrewName());


        RtMachine machineByMachCode = getMachineByMachCode(params.getMachCode());
        consumeMaster.setCompanyCode(machineByMachCode.getCompanyCode());
        consumeMaster.setCompanyName(machineByMachCode.getCompanyName());
        consumeMaster.setCompanyId(requestParams.getCompanyId());
        consumeMaster.setCwocCode(machineByMachCode.getCwocCode());
        consumeMaster.setCwocName(machineByMachCode.getCwocName());
        consumeMaster.setMachCode(machineByMachCode.getMachCode());
        consumeMaster.setMachName(machineByMachCode.getMachName());
        consumeMaster.setIsCanceled(0);
        consumeMaster.setIsClosed(0);

        consumeMaster.setEnterCode(principal.getName());
        consumeMaster.setEnterName(principal.getName());
        consumeMaster.setEnterTime(new Date());

        consumeMaster.setUserTxt1(params.getUserText1());
        consumeMaster.setUserTxt1Name(params.getUserText1Name());
        consumeMaster.setUserTxt2(params.getUserText2());
        consumeMaster.setUserTxt2Name(params.getUserText2Name());


        MfgConsumeDetail consumeDetail = new MfgConsumeDetail();
        //   consumeDetail.setId(identityService.getIdentity());
        //  consumeDetail.setMasterId(consumeMaster.getId());
        consumeDetail.setDocCode(consumeMaster.getDocCode());


        consumeDetail.setEnterCode(principal.getName());
        consumeDetail.setEnterName(principal.getName());
        consumeDetail.setEnterTime(new Date());
        consumeDetail.setSystemId(requestParams.getSystemId());
        consumeDetail.setPeriodId(periodId);


        mfgConsume.setMfgConsumeDetail(consumeDetail);
        mfgConsume.setMfgConsumeMaster(consumeMaster);

        return mfgConsume;
    }

    @Override
    public MfgConsume addMatInventoryInfo(MatInventoryInfo matInventoryInfo, MfgConsume mfgConsume) {
        MfgConsumeMaster consumeMaster = mfgConsume.getMfgConsumeMaster();
        consumeMaster.setMatCode(matInventoryInfo.getMatCode());
        consumeMaster.setMatName(matInventoryInfo.getMatName());
        consumeMaster.setMatType(matInventoryInfo.getMatType());
        consumeMaster.setBeginTime(new Date());
        consumeMaster.setUom(matInventoryInfo.getUom());

        MfgConsumeDetail consumeDetail = mfgConsume.getMfgConsumeDetail();

        consumeDetail.setMatCode(consumeMaster.getMatCode());
        consumeDetail.setMatName(consumeMaster.getMatName());
        consumeDetail.setBatchCode(matInventoryInfo.getBatchCode());
        consumeDetail.setBatchName(matInventoryInfo.getBatchName());
        consumeDetail.setUom(matInventoryInfo.getUom());

        return mfgConsume;
    }

    @Override
    public String getProdBachByOrder(WoOrder order) {
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setConditions(Collections.singletonList(new Condition("woOrder", "eq", order.getWoOrder(),
                null)));
        pageAndCondition.setPagination(new Pagination(1L, 10L));
        ResponseEntity<Result<IPage<WoOperationCompleteDetail>>> operationCompletePage =
                operationCompleteDetailFeignService.page(pageAndCondition);

        if (operationCompletePage.getBody() != null && operationCompletePage.getBody().getData().getRecords().size() != 0) {
            return operationCompletePage.getBody().getData().getRecords().stream().findFirst().get().getProdBatch();
        } else {
            return null;
        }
    }

    @Override
    public void addOperationComplete(WoOrder order, String prodBatch, Long asId, Boolean isOrderStart,
                                     Principal principal) {
        WoOperationCompleteMaster operationCompleteMaster = new WoOperationCompleteMaster();
        //      operationCompleteMaster.setId(identityService.getIdentity());
//        operationCompleteMaster.setDocCode(iBusinessNumberControllerFeign.nextId(order.getSystemId(),
//                order.getFormId(), "woOperationComplete", "sfc", new HashMap<>()).getBody());
//        operationCompleteMaster.setDocDate(LocalDate.now());
//        operationCompleteMaster.setDocStatus(0);

        Long periodId = this.getPeriodId();

        operationCompleteMaster.setEnterCode(principal.getName());
        operationCompleteMaster.setEnterName(principal.getName());
        operationCompleteMaster.setEnterTime(new Date());
        operationCompleteMaster.setMachCode(order.getMachineCode());
        operationCompleteMaster.setMachName(order.getMachineName());
        operationCompleteMaster.setStorageCode(order.getStroageCode());
        operationCompleteMaster.setStorageName(order.getStroageName());
        operationCompleteMaster.setWoOrderId(order.getId());
        operationCompleteMaster.setSystemId(requestParams.getSystemId());
        operationCompleteMaster.setCompanyId(requestParams.getCompanyId());
        operationCompleteMaster.setPeriodId(periodId);
        operationCompleteMaster.setFormId(order.getFormId());
//        RtMachine machine = sfcService.getMachineByMachCode(order.getMachineCode());
//        operationCompleteMaster.setCompanyId(machine.getCompanyId());
//        operationCompleteMaster.setCompanyName(machine.getCompanyName());
//        operationCompleteMaster.setCompanyCode(machine.getCompanyCode());

        operationCompleteMaster.setPlantCode(order.getPlantCode());
        operationCompleteMaster.setPlantName(order.getPlantName());

        operationCompleteMaster.setCwocCode(order.getWorkCenterCode());
        operationCompleteMaster.setCwocName(order.getWorkCenterName());

        MfgUserEnvironment user = getUserEnvironmentByUserCode(principal.getName());
        operationCompleteMaster.setCrewCode(user.getCrewCode());
        operationCompleteMaster.setCrewName(user.getCrewName());


        WoOperationCompleteDetail operationCompleteDetail = new WoOperationCompleteDetail();
        //   operationCompleteDetail.setId(identityService.getIdentity());
        //  operationCompleteDetail.setMasterId(operationCompleteMaster.getId());
        operationCompleteDetail.setDocCode(operationCompleteMaster.getDocCode());
        operationCompleteDetail.setWoOrder(order.getWoOrder());
        operationCompleteDetail.setPeriodId(periodId);
        if (prodBatch != null) {
            operationCompleteDetail.setProdBatch(prodBatch);
        }
        if (asId != null) {
            operationCompleteDetail.setUsrTxt1(asId.toString());
        }
        if (isOrderStart) {
            operationCompleteDetail.setStartTime(new Date());
        }
        operationCompleteDetail.setEnterCode(principal.getName());
        operationCompleteDetail.setEnterName(principal.getName());
        operationCompleteDetail.setEnterTime(new Date());

        operationCompleteDetail.setMatCode(order.getMatCode());
        operationCompleteDetail.setMatName(order.getMatName());
        operationCompleteDetail.setCompanyId(requestParams.getCompanyId());
        operationCompleteDetail.setSystemId(requestParams.getSystemId());

        operationCompleteMaster.setDetailList(Collections.singletonList(operationCompleteDetail));

        ResponseEntity<Result> add = operationCompleteFeignService.add(operationCompleteMaster);
        if (add.getBody() != null && add.getBody().getCode() != 0) {
            throw new RuntimeException("新增工序完工单失败");
        }
    }

    @Override
    public GuideMaster generateWipStockOrderInfo(Long boxId, Long formId, WipStorageBin wipStorageBin,
                                                 RtWorkCenter workCenter,
                                                 List<LcmBoxFillDetail> lcmBoxFillDetails) {
        Long periodId = this.getPeriodId();
        GuideMaster guideMaster = new GuideMaster();
        List<GuideDetail> guideDetails = new ArrayList<>();
        //根据工作中心代码获取车间信息
        guideMaster.setStorageCode(workCenter.getStorageCode());
        guideMaster.setStorageName(workCenter.getStorageName());
        guideMaster.setBinId(wipStorageBin.getId());
        guideMaster.setBinName(wipStorageBin.getBinName());
        guideMaster.setBinCode(wipStorageBin.getBinCode());
        guideMaster.setCompanyId(requestParams.getCompanyId());
        guideMaster.setSystemId(requestParams.getSystemId());
        guideMaster.setPeriodId(periodId);
        guideMaster.setFormId(formId);

        for (LcmBoxFillDetail lcmBoxFillDetail : lcmBoxFillDetails) {
            GuideDetail guideDetail = new GuideDetail();
            guideDetail.setBoxCode(lcmBoxFillDetail.getRefBoxCode());
            guideDetail.setMatCode(lcmBoxFillDetail.getMatCode());
            guideDetail.setDigit(lcmBoxFillDetail.getDigit());
            guideDetail.setWeight(lcmBoxFillDetail.getTheoryWeight());
            guideDetail.setLoadBoxDocCode(lcmBoxFillDetail.getDocCode());
            guideDetail.setPeriodId(periodId);
            ResponseEntity<com.diligent.cloud.primary.data.model.Result> woOrderResult =
                    orderFeignService.selectById(Long.valueOf(lcmBoxFillDetail.getRefWoOrder()));
            Preconditions.checkNotNull(woOrderResult.getBody(), "此[%s]id查询不到工单信息",
                    lcmBoxFillDetail.getRefWoOrder());
            WoOrder woOrder = (WoOrder) woOrderResult.getBody().getData();

            guideDetail.setBatchCode(woOrder.getBatchCode());
            guideDetail.setCwocCode(woOrder.getWorkCenterCode());
            guideDetail.setCwocName(woOrder.getWorkCenterName());
            guideDetail.setWoOrderCode(woOrder.getWoOrder());
            guideDetail.setWoOrderId(woOrder.getId());
            guideDetail.setBoxId(boxId);

            guideDetails.add(guideDetail);
        }

        guideMaster.setGuideDetails(guideDetails);
        return guideMaster;
    }

    @Override
    public Long getPeriodId() {
        ResponseEntity<ObjectResult<Period>> periodIdResult = mdmBaseFeignService.getPeriodId();
        Preconditions.checkNotNull(periodIdResult.getBody(), "查询不到PeriodId");
        return periodIdResult.getBody().getData().getId().longValue();
    }

    @Override
    public String getMatType(String matType) {

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mdmMatTypeResult =
                mdmMatTypeFeignService.selectDataByCondition(Collections.singletonList(new Condition("name", "eq",
                        matType, null)));
        Preconditions.checkNotNull(mdmMatTypeResult.getBody(), "查询不到此[%s]物料类型", matType);
        if (mdmMatTypeResult.getBody() != null && mdmMatTypeResult.getBody().getCode() == 0) {
            List<LinkedHashMap> matTypes = (List<LinkedHashMap>) mdmMatTypeResult.getBody().getData();
            if (matTypes.size() != 0) {
                MdmMatType mdmMatType = JSON.parseObject(JSON.toJSONString(matTypes.stream().findFirst().get()),
                        MdmMatType.class);
                return mdmMatType.getCode();
            }
        }
        return null;
    }

    @Override
    public Map<String, Integer> getProjectMatchingRate(Integer orderType, String projectName, String machCode) {
        PageAndCondition pageAndCondition = new PageAndCondition();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("orderType", "eq", orderType, null));
        conditions.add(new Condition("orderStatus", "eq", 4, null));
        conditions.add(new Condition("projectName", "eq", projectName, null));

        pageAndCondition.setConditions(conditions);
        pageAndCondition.setPagination(new Pagination(1L, 1L));

        ResponseEntity<Result<IPage<WoOrder>>> page = orderFeignService.page(pageAndCondition);

        pageAndCondition.setPagination(new Pagination(1L, page.getBody().getData().getTotal()));

        ResponseEntity<Result<IPage<WoOrder>>> page1 = orderFeignService.page(pageAndCondition);


        RtMachine machineByMachCode = getMachineByMachCode(machCode);
        Preconditions.checkNotNull(machineByMachCode, "查询不到此机台");
        RtWorkCenter workCenterByCwocCode = getWorkCenterByCwocCode(machineByMachCode.getCwocCode());
        Preconditions.checkNotNull(workCenterByCwocCode, "查询不到此车间");
        Integer total = 0;
        for (WoOrder order : page1.getBody().getData().getRecords()) {
            order.getDeliveryDigit();

            ObjectResult<WipStorageLedger> ledger =
                    wipStorageLedgerFeignService.getLedger(workCenterByCwocCode.getStorageCode(), order.getMatCode(),
                            null, order.getSystemId());
            if (order.getDeliveryDigit().intValue()!=0){
                total += ledger.getData().getDigit().intValue() / order.getDeliveryDigit().intValue();
            }
        }
        Map<String, Integer> answer = new HashMap<>();
        answer.put("total", total);
        answer.put("matCodeNb", page.getBody().getData().getTotal().intValue());
        return answer;
    }


}
